﻿using UnityEngine;
using System.Collections;

public class ObjectScript : MonoBehaviour {
	
//	float sinewave = 0.0f;
	public Vector2 startTouch = Vector2.zero; // Initialise the values to zero
	
	public GameObject prefab;
	private Texture originalTexture;
	public Texture touchTexture;

	// Use this for initialization
	void Start () {
		// Get the current texture applied to the object
		originalTexture = this.gameObject.renderer.material.mainTexture;
	}
	
	// Update is called once per frame
	void Update () {
//		sinewave += 0.1f;
//		this.transform.Translate (Mathf.Cos (sinewave)/20, Mathf.Sin (sinewave)/20, 0);
	}
	
//	void OnMouseDown () {
//		Debug.Log("You pressed the cube?");
//	}
	
	public void HandleTouchInput(Touch touch)
	{
		
		// Find the game object
		GameObject cube = GameObject.Find ("Cube");
		
		switch(touch.phase)
		{
		case TouchPhase.Began:	// Handles the start of touch
			
				
			// Get the Ray object based on the position of touch
			Ray ray = Camera.main.ScreenPointToRay(touch.position);
			
			RaycastHit hit; // store the information of object selected
			
			if(Physics.Raycast(ray, out hit)) // if raycase hits an object
			{
				if(hit.collider.gameObject == cube) // if object hit is the cube
					// Replace the texture with another
					this.gameObject.renderer.material.mainTexture = touchTexture;
			}
			
			// Get the position where touch begins
			startTouch = touch.position;
			
			// Create a spawn position based on touch position
			Vector3 spawnPos = touch.position;
			spawnPos.z = 10; // 10 unit into the screen from camera position
			
			// Convert from screen position to world position
			Vector3 worldPos = Camera.main.ScreenToWorldPoint (spawnPos);
			
			// Instantiate the object at position and default rotation
			GameObject obj = Instantiate (prefab, worldPos, Quaternion.identity) as GameObject;
			obj.name = "Cube 2";
			obj.tag = "Interactive";
			Color newcolor = Color.black;
			newcolor.r = Random.Range(0.0f, 1.0f);
			newcolor.g = Random.Range(0.0f, 1.0f);
			newcolor.b = Random.Range(0.0f, 1.0f);
			obj.renderer.material.color = newcolor;
			
			break;
			
		case TouchPhase.Canceled:
			break;
			
		case TouchPhase.Ended:	// Handles touch is released
			
			// Reset back to original texture
			this.gameObject.renderer.material.mainTexture = originalTexture;
			
			// Find the directino when touch ends
//			Vector2 swipeDir = touch.position - startTouch;
			
//			if(swipeDir.x > 0) // moving to the right side?
//				cube.transform.Rotate (0, -10, 0);
//			else if(swipeDir.x < 0)
//				cube.transform.Rotate (0, 10, 0);
			
			break;
			
		case TouchPhase.Moved:	// Handles touch has moved
			
			// Find the difference in position from the last touch
			Vector2 dir = touch.deltaPosition;
		
			if(dir.x > 0) cube.transform.Rotate(0, -1, 0);
			else if(dir.x < 0) cube.transform.Rotate (0, 1, 0);
			
			break;
			
		case TouchPhase.Stationary:
			break;
		}
	}
}
